package org.example.queueadmin.dlq;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Base64;
import java.util.List;

@Service
@RequiredArgsConstructor
public class DeadLetterService {
  private final RedisTemplate<String, byte[]> redisBytes;
  private final StringRedisTemplate redisStrings;

  private String key(Long taskId) { return "dlq:" + taskId; }

  public void push(Long taskId, byte[] payload, String reason) {
    String metaKey = key(taskId)+":meta:"+Instant.now().toEpochMilli();
    redisBytes.opsForList().leftPush(key(taskId), payload);
    redisStrings.opsForValue().set(metaKey, reason);
  }

  public List<String> rangeBase64(Long taskId, long start, long count) {
    List<byte[]> bytes = redisBytes.opsForList().range(key(taskId), start, start + count - 1);
    return bytes == null ? List.of() : bytes.stream().map(b -> Base64.getEncoder().encodeToString(b)).toList();
  }

  public void clear(Long taskId) {
    redisBytes.delete(key(taskId));
  }
}

